﻿using Blazored.LocalStorage;
using Bookify.Web.DTO.User;
using Bookify.Web.Providers;
using Bookify.Web.Services.Auth;
using Bookify.Web.Services.Base;
using Masa.Blazor;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Options;
using System.Text.Json;
using LoginUserRequest = Bookify.Web.DTO.User.LoginUserRequest;

namespace Bookify.Web.Services.User
{
    public class UserCaller : BaseHttpService
    {
        private readonly AuthenticationStateProvider _authenticationStateProvider;

        public UserCaller(IClient client, ILocalStorageService localStorageService, IOptions<ServiceOptions> options, AuthenticationStateProvider authenticationStateProvider) : base(client, localStorageService, options)
        {
            this._authenticationStateProvider = authenticationStateProvider;
        }

        public async Task<bool> LoginAsync(string email, string password)
        {
            var client = await CreateClientAsync();
            var request = new LoginUserRequest(email, password);
            var response = await client.PostAsJsonAsync("/api/Users/login", request);
            //response.EnsureSuccessStatusCode();
            if (response.IsSuccessStatusCode)
            {
                string token = await response.Content.ReadAsStringAsync();
                var userToken = JsonSerializer.Deserialize<UserToken>(token);
                
                await _localStorageService.SetItemAsync("token", userToken?.accessToken);

                // 设置Claims和登录状态
                var provider = ((AuthProvider)_authenticationStateProvider);
                provider.JwtToken = userToken?.accessToken;
                //await ((AuthProvider)_authenticationStateProvider).GetAuthenticationStateAsync();
                ((AuthProvider)_authenticationStateProvider).LoggedIn();

                return true;
            }
            else
            {
                return false;
            }
        }

        public async Task LogoutAsync()
        {
            await _localStorageService.RemoveItemAsync("token");
            ((AuthProvider)_authenticationStateProvider).Logout();
        }
    }
}
